﻿using Microsoft.JSInterop;
using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Rmac.Uitls
{
    public static class StringUtils
    {
        /// <summary>
        /// 压缩字符串
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [JSInvokable]
        public static string Compress(string originalString)
        {
            byte[] data = System.Text.Encoding.UTF8.GetBytes(originalString);

            using (MemoryStream compressedStream = new MemoryStream())
            using (GZipStream compressionStream = new GZipStream(compressedStream, CompressionMode.Compress))
            {
                compressionStream.Write(data, 0, data.Length);
                compressionStream.Close();
                return Convert.ToBase64String(compressedStream.ToArray());
            }
        }
        /// <summary>
        /// 解压缩字符串
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [JSInvokable]
        public static string Decompress(string compressedString)
        {
            // 将压缩后的字符串转换为字节数组
            byte[] data = Convert.FromBase64String(compressedString);

            using (MemoryStream compressedStream = new MemoryStream(data))
            using (GZipStream decompressionStream = new GZipStream(compressedStream, CompressionMode.Decompress))
            using (MemoryStream decompressedStream = new MemoryStream())
            {
                decompressionStream.CopyTo(decompressedStream);
                return System.Text.Encoding.UTF8.GetString(decompressedStream.ToArray());
            }
        }
    }
}
